import { AuthService } from '@app/core';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
})
export class LoginComponent implements OnInit, OnDestroy {
  message: string;
  loginForm = this.fb.group({
    account: [''],
    password: [''],
  });
  constructor(
    private fb: FormBuilder,
    private auth: AuthService,
    private router: Router
  ) {}

  ngOnDestroy(): void {}

  ngOnInit(): void {
    this.loginForm.valueChanges.subscribe(() => (this.message = ''));
  }

  login(): void {
    this.auth
      .authenticate(
        this.loginForm.get('account').value,
        this.loginForm.get('password').value
      )
      .subscribe(
        (isLogin) => {
          if (isLogin) {
            const url = this.auth.redirectUrl || '/';
            this.router.navigateByUrl(url);
          }
        },
        (error) => (this.message = error)
      );
  }
}
